const Sequelize = require("sequelize");

const {
    DATABASE,
    USERNAME,
    PASSWORD,
    PORT,
    HOST
} = require('./config').database

const sequelize = new Sequelize(DATABASE, USERNAME, PASSWORD, {
    host: HOST, //数据库地址
    port: PORT,
    dialect: 'mysql', //指定连接的数据库类型
    pool: {
        max: 5, //连接池最大连接数量
        min: 0, //最小连接数量
        idle: 10000, //如果一个线程 10秒内么有被使用过的话，就释放
    },
    timezone: '+08:00', //for writing to database
    // logging: true, // 执行过程会log一些SQL的logging，设为false不显示
    // logging: function () {
    //     console.log(this)
    // },
    define: {
        timestamps: true,
        timestamp: { //我们自己定义的时间戳字段
            // type: DATE,
            defaultValue: Date.now()
        },
        createdAt: 'created_at',
        updatedAt: 'updated_at',
        deletedAt: 'deleted_at',
    }
})
// 创建模型
// sequelize.sync({
//     force: false
// })

sequelize
    .authenticate()
    .then(async () => {
        const Disease = require('../models/disease');
        const DiseaseType = require('../models/diseaseType');
        Disease.belongsToMany(DiseaseType, { through: 'Dis_DisType' }); 
        DiseaseType.belongsToMany(Disease, { through: 'Dis_DisType' });

        const user = require('../models/user');
        Disease.belongsToMany(user, { through: 'Dis_User' }); 
        user.belongsToMany(Disease, { through: 'Dis_User' });
        // sequelize.sync({
        //     force: true
        // }).then(async () => {}).catch(err => {
        //     console.error('---------------------', err);
        // });
    })
.catch(err => {
    console.error('Unable to connect to the database:', err);
});

module.exports = {
    sequelize
}